﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SenerPro;
using System.IO;
using System.Text;

namespace MensUnoShop.Models
{
    public class MemberFactory
    {
        private static Logger _log = new Logger(Config.logpath);
        public static bool AddNormalMember(string _email, string _password, string _firstname, string _lastname, string _telh, string _telo, string _mobile, bool _ismarried, bool _sex, string _birth, string _edu, string _job, string _income, string _country, string _zip, string _city, string _area, string _address, bool _isedm)
        {
            DBMember dbm = new DBMember();
            string mguid = string.Empty;
            if (dbm.AddNewMember(_email, _password, _firstname, _lastname, _telh, _telo, _mobile, _ismarried, _sex, _birth, _edu, _job, _income, _country, _zip, _city, _area, _address, _isedm, ref mguid))
            {
                //發送通知信
                string mailcontent = File.ReadAllText(HttpContext.Current.Server.MapPath(Config.Latter_Join)).Replace("[fname]", _firstname).Replace("[lname]", _lastname).Replace("[mguid]", mguid);
                string error;
                //Tools.SendMail("加入會員確認信", mailcontent, _email, _firstname + "," + _lastname, Config.SMTPServer, new System.Net.Mail.MailAddress("system@mensunoshop.com", "Men's Uno Shop"), out error);

                return Config.SendMail("加入會員確認信", mailcontent, _email, _firstname + "," + _lastname);
            }
            else
                return false;
        }

        public static bool StartNewMember(string mguid, ref string msg)
        {
            Guid mm;
            bool ischeck = false;
            if (Guid.TryParse(mguid, out mm))
            {
                DBMember dbm = new DBMember();
                ischeck = dbm.StartNewMember(mm, ref msg);
                if (ischeck)
                {
                    Member m = dbm.GetMember(mm);
                    //發送通知信
                    string mailcontent = File.ReadAllText(HttpContext.Current.Server.MapPath(Config.Latter_Join_Success)).Replace("[email]", m.EMAIL).Replace("[password]", m.PASSWORD);
                    Config.SendMail("會員註冊成功通知信", mailcontent, m.EMAIL, m.FIRSTNAME + "," + m.LASTNAME);
                }
            }
            else
                msg = "序號驗證失敗!!";
            return ischeck;
        }

        public static bool CheckMemberLogin(string email, string pwd, ref string err)
        {
            bool ischeck = false;
            err = "帳號密碼錯誤!!";
            if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(pwd))
            {
                DBMember dbm = new DBMember();
                ischeck = dbm.CheckMemberLogin(email, pwd,ref err);
                if (ischeck)
                {
                    Member m = new Member(email);
                    m.GetMemberData();
                    m.UptMemberLastLogin(HttpContext.Current.Request.UserHostAddress);
                    m.UptCookie();
                }
            }
            return ischeck;
        }

        public static Member GetMember()
        {
            try
            {
                //清購物車
                HttpCookie hc = HttpContext.Current.Request.Cookies["ispay"];
                if (hc != null && hc.Value == "200")
                {
                    ShoppingCart sc = new ShoppingCart();
                    sc.FreeCookie();
                    sc = null;
                    HttpCookie cc = new HttpCookie("ispay");
                    cc.Expires = DateTime.Now.AddHours(-1);
                    HttpContext.Current.Response.Cookies.Add(cc);
                }

                Member im = (Member)HttpContext.Current.Session["mm"];
                if (im == null)
                {
                    HttpCookie hk = HttpContext.Current.Request.Cookies["mm"];
                    if (hk != null)
                    {
                        im = (Member)Tools.DeSerialize(Tools.FormBase64URLString(BlowFish.Decrypt(hk.Value, "mavi")));
                    }
                }
                else
                {
                    //檢查有沒有登入的活動
                    //登入期間內只檢查一次
                    if (HttpContext.Current.Session["HavingCheckedActivity"] == null)
                    {
                        List<SalesKit> sklist = SalesKitFactory.GetByLoginGiftSalesKitList();
                        List<string> lskr = new List<string>();
                        foreach (ILoginSalesKit sk in sklist)
                        {
                            sk.Judge(im);

                            if (sk.ISMEET)
                            {
                                sk.Do(im);
                                lskr.Add(sk.GetResultString());
                            }
                        }
                        if (lskr.Count > 0)
                            HttpContext.Current.Session["LoginSalesKitResponse"] = lskr;
                        HttpContext.Current.Session["HavingCheckedActivity"] = true;
                    }
                }
                return im;
            }
            catch (Exception ex)
            {
                _log.RecordException(_log.DBExceptionPath, "[GetMember]" + ex.ToString());
                return null;
            }
        }

        public static bool UptMemberData(Member m)
        {
            DBMember dbm = new DBMember();
            try
            {
                dbm.UptMemberData(m);
                return true;
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "UptMemberData", ex.ToString());                
            }
            return false;

            //bool ischeck = false;
            //if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(pwd))
            //{
            //    DBMember dbm = new DBMember();
            //    ischeck = dbm.CheckMemberLogin(email, BlowFish.Encrypt(pwd, Config.key));
            //    if (ischeck)
            //    {
            //        Member m = new Member(email);
            //        m.GetMemberData();
            //        m.UptMemberLastLogin(HttpContext.Current.Request.UserHostAddress);
            //        m.UptCookie();
            //    }
            //}
            //return ischeck;
        }

        public static bool UptMember(Guid _mguid, string email, string kpass, bool status)
        {
            DBMember dbm = new DBMember();
            try
            {
                dbm.UptMember(_mguid, email, kpass, status);
                return true;
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "UptMember", ex.ToString());
            }
            return false;
                       
        }

        public static bool NotifyPwd(string email)
        {
            DBMember dbm = new DBMember();
            UMember m = new UMember();
            try
            {
                m = dbm.GetMember(email);
                if (m != null)
                {                    
                    //發送密碼通知信
                    string mailcontent = File.ReadAllText(HttpContext.Current.Server.MapPath(Config.Latter_Forget_Password)).Replace("[email]", m.Memail).Replace("[pass]", m.MKpass);
                    return Config.SendMail("密碼通知確認信", mailcontent, m.Memail, "");
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "NotifyPwd", ex.ToString());
            }
            return false;
        }

        //會員登出
        public static void MemberFree()
        {
            HttpCookie hk = new HttpCookie("mm", "");
            hk.Expires = DateTime.Now.AddMinutes(-1);
            HttpContext.Current.Response.Cookies.Add(hk);
            HttpContext.Current.Session["mm"] = null;
        }

        public static List<MemberFavorite> GetMemberFavorite(Guid _mguid)
        {
            DBMember dbm = new DBMember();
            List<UMemberFavorite> _umfList = new List<UMemberFavorite>();
            List<MemberFavorite> _mfList = new List<MemberFavorite>();
            
            try
            {
                _umfList = dbm.GetMemberFavorite(_mguid);
                
                foreach (var item in _umfList)
                {
                    IMarket _nm = MarketFactory.GetMarket(item.MFmkguid,(Config.MarketType)item.MFmktype);

                    MemberFavorite _mf = new MemberFavorite();
                    _mf.MFID = item.MFid;
                    _mf.MFMGUID = item.MFmguid;
                    _mf.MFDATEIN = item.MFdatein;
                    _mf.MFMKGUID = item.MFmkguid;
                    _mf.MFPRODUCTGUID = item.MFproductid;
                    _mf.MFSPECGUID = item.MFspecid;
                    _mf.MKTYPE = (Config.MarketType)item.MFmktype;
                    _mf.MFMKSN = _nm.SN;
                    //判斷user選擇的最愛
                    foreach (var a in _nm.PRODUCTLIST)
                    {                        
                        if (a.PDGUID == item.MFproductid)
                        {
                            _mf.MFPRODUCTTITLETAGID = a.TITLETAGID;
                            a.GetSpecification();
                            foreach (var b in a.SPEC)
                            {
                                if (b.SID == item.MFspecid)
                                {
                                    _mf.MFSPECTITLE = b.TITLE;
                                    _mf.MFSTOCK = b.STOCK;
                                    break;
                                }
                            }
                        }
                    }

                    _mf.MFPIC = _nm.IMG;
                    _mf.MFPRICE = _nm.PRICE;
                    _mf.MFMKTITLE = _nm.TITLE;
                                        
                    _mfList.Add(_mf);
                }

            }
            catch (Exception ex)
            {
                _log.RecordExceptionFormat(_log.FlowLogPath, "GetMemberFavorite", ex.ToString());
            }
            return _mfList;
        }

        public static bool DelMemberFavorite(Guid _mfid)
        { 
            DBMember dbm = new DBMember();
            return dbm.DelMemberFavorite(_mfid);
        }

        public static bool AddMemberFavorite(Guid _mguid, Guid mkguid, Guid productid, Guid specid)
        {
            DBMember dbm = new DBMember();
            return dbm.AddMemberFavorite(_mguid, mkguid, productid, specid);
        }

        public static List<Member> GetMemberList(string querychoice, string querycontent)
        {
            DBMember dbm = new DBMember();
            List<Member> memberlist = new List<Member>();
            memberlist = dbm.GetMemberList(querychoice, querycontent);
            
            return memberlist;
        }

        public static Member GetMember(Guid mguid)
        {
            DBMember dbm = new DBMember();
            Member member = new Member();
            member = dbm.GetMember(mguid);
            return member;
        }

        public static bool SetEdm(string email)
        {
            DBMember dbm = new DBMember();
            return dbm.SetEdm(email);
        }
    }
}